package com.toivan.mt.adapter;

import android.os.Handler;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hwangjr.rxbus.RxBus;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.dispatcher.DownloadDispatcher;
import com.liulishuo.okdownload.core.listener.DownloadListener2;
import com.toivan.mt.R;
import com.toivan.mt.model.MtPortrait;
import com.toivan.mt.model.RxBusAction;
import com.toivan.mt.utils.MtSharedPreferences;
import com.toivan.mt.utils.MtUnZip;
import com.toivan.sdk.MtSDK;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName MtPortraitAdapter
 * @Description 抠图效果列表的适配器
 * @Author yang
 * @Date 2021/6/22 10:48
 */
public class MtPortraitAdapter extends RecyclerView.Adapter<MtPortraitAdapter.MtPortraitViewHolder> {

    private int selectedPosition = MtSharedPreferences.getInstance().getPortraitPosition();


    private final Handler handler = new Handler();

    private final List<MtPortrait> list;

    private final Map<String, String> downloadingPortrait = new ConcurrentHashMap<>();


    public MtPortraitAdapter(List<MtPortrait> list) {
        this.list = list;
        DownloadDispatcher.setMaxParallelRunningCount(5);
    }


    @NonNull @Override public MtPortraitViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mt_sticker, parent, false);
        return new MtPortraitViewHolder(view);
    }


    @Override public void onBindViewHolder(@NonNull final MtPortraitAdapter.MtPortraitViewHolder holder, int position) {
        final MtPortrait portrait = list.get(holder.getAdapterPosition());

        if (selectedPosition == position) {
            holder.itemView.setSelected(true);
        } else {
            holder.itemView.setSelected(false);
        }

        //显示封面
        Glide.with(holder.itemView.getContext())
            .load(list.get(position).getThumb())
            .into(holder.thumbIV);

        //判断是否已经下载
        if (portrait.getDownloaded()) {
            holder.downloadIV.setVisibility(View.GONE);
            holder.loadingIV.setVisibility(View.GONE);
            holder.stopLoadingAnimation();
        } else {
            //判断是否正在下载，如果正在下载，则显示加载动画
            if (downloadingPortrait.containsKey(portrait.getName())) {
                holder.downloadIV.setVisibility(View.GONE);
                holder.loadingIV.setVisibility(View.VISIBLE);
                holder.startLoadingAnimation();
            } else {
                holder.downloadIV.setVisibility(View.VISIBLE);
                holder.loadingIV.setVisibility(View.GONE);
                holder.stopLoadingAnimation();
            }
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View view) {

                if (!portrait.getDownloaded()) {
                    //未下载的处理

                    //如果已经在下载了，则不操作
                    if (downloadingPortrait.containsKey(portrait.getName())) {
                        return;
                    }

                    new DownloadTask.Builder(portrait.getUrl(), new File(MtSDK.get().getPortraitPath()))
                        .setMinIntervalMillisCallbackProcess(30)
                        .setConnectionCount(1)
                        .build()
                        .enqueue(new DownloadListener2() {
                            @Override public void taskStart(@NonNull DownloadTask task) {
                                downloadingPortrait.put(portrait.getName(), portrait.getUrl());
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        notifyDataSetChanged();
                                    }
                                });
                            }


                            @Override public void taskEnd(@NonNull DownloadTask task, @NonNull final EndCause cause, @Nullable final Exception realCause) {
                                if (cause == EndCause.COMPLETED) {
                                    downloadingPortrait.remove(portrait.getName());
                                    File targetDir = new File(MtSDK.get().getPortraitPath());
                                    File file = task.getFile();
                                    try {
                                        //解压到贴纸目录
                                        if (file != null) {
                                            MtUnZip.unzip(file, targetDir);
                                            file.delete();
                                        }

                                        //修改内存与文件
                                        portrait.setDownloaded(true);
                                        portrait.portraitDownload(holder.itemView.getContext());

                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                notifyDataSetChanged();
                                            }
                                        });

                                    } catch (Exception e) {
                                        if (file != null) {
                                            file.delete();
                                        }
                                    }

                                } else {
                                    //退出队列
                                    downloadingPortrait.remove(portrait.getName());
                                    //弹出toast提示
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            notifyDataSetChanged();
                                            if (realCause != null) {
                                                Toast.makeText(holder.itemView.getContext(), realCause.getMessage(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                }
                            }
                        });

                } else {
                    //下载过的处理
                    if (holder.getAdapterPosition() == RecyclerView.NO_POSITION) {
                        return;
                    }

                    MtSDK.get().setPortraitName(portrait.getName());
                    MtSharedPreferences.getInstance().setPortraitName(portrait.getName(), holder.getAdapterPosition());

                    int lastPosition = selectedPosition;
                    selectedPosition = holder.getAdapterPosition();
                    notifyItemChanged(selectedPosition);
                    notifyItemChanged(lastPosition);

                    RxBus.get().post(RxBusAction.ACTION_ENABLE_CANCEL, "");

                }
            }
        });

    }


    @Override public int getItemCount() {
        return list == null ? 0 : list.size();
    }


    class MtPortraitViewHolder extends RecyclerView.ViewHolder {

        public ImageView thumbIV, downloadIV, loadingIV;


        public MtPortraitViewHolder(@NonNull View itemView) {
            super(itemView);
            thumbIV = itemView.findViewById(R.id.thumbIV);
            downloadIV = itemView.findViewById(R.id.downloadIV);
            loadingIV = itemView.findViewById(R.id.loadingIV);
        }


        public void startLoadingAnimation() {
            Animation animation = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.loading_animation);
            loadingIV.startAnimation(animation);
        }


        public void stopLoadingAnimation() {
            loadingIV.clearAnimation();
        }
    }


    public void cancelSelected() {
        selectedPosition = -1;
        MtSDK.get().setPortraitName("");
        MtSharedPreferences.getInstance().setPortraitName("", selectedPosition);
        notifyDataSetChanged();
    }

}
